package test6;

import java.util.Arrays;

/**
 * @title:
 * @description:
 * @Author 易俊杰
 * @data: 2022/7/25 9:06
 * @version: V1.0
 */
public class Demo3 {
    public static void main(String[] args) {
        int[] arr = {2, 1, 3};
        nextPermutation(arr);
    }

    public static void nextPermutation(int[] nums) {
        if (nums.length == 1 || nums.length == 0) {
            System.out.println(Arrays.toString(nums));
            return;
        }

        if (nums.length == 2) {
            int t = nums[0];
            nums[0] = nums[1];
            nums[1] = t;
            System.out.println(Arrays.toString(nums));
            return;
        }
        //使用滑动窗口，窗口大小为 3 从右往左
        int r = nums.length - 1;
        int l = r - 2;

        int flag = 0;//标记是否触发下面规则，否则就是由大到小
        while (l >= 0) {
            int a1 = nums[l];
            int a2 = nums[l + 1];
            int a3 = nums[r];
            int t;
            //小中大
            if (a2 < a3) {
                t = nums[r];
                nums[r] = nums[l + 1];
                nums[l + 1] = t;
                flag = 1;
                break;
            }
            //中大小
            if (a3 <= a1 && a1 < a2) {
                t = nums[l];
                nums[l] = nums[l + 1];
                nums[l + 1] = t;
                t = nums[l + 1];
                nums[l + 1] = nums[r];
                nums[r] = t;
                //l 后面的数字从小到大排个序

                flag = 1;
                break;
            }
            //小大中
            if (a1 < a3 && a3 < a2) {
                t = nums[r];
                nums[r] = nums[l + 1];
                nums[l + 1] = t;
                t = nums[l + 1];
                nums[l + 1] = nums[l];
                nums[l] = t;
                //l 后面的数字从小到大排个序

                flag = 1;
                break;
            }
            l--;
            r--;
        }
        if (flag == 0) {
            Arrays.sort(nums);
            System.out.println(Arrays.toString(nums));
        } else {
            System.out.println(Arrays.toString(nums));
        }
    }
}
